package mygang.dao;

import java.util.List;
import mygang.model.User;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 */
@Repository("userDAO")
@Transactional
class UserDAOImpl extends AbstractDAO implements UserDAO {
    
    private static final Logger log = Logger.getLogger(AbstractDAO.class.toString());

    @Transactional(readOnly = false)
    public void save(User user) {
        log.debug("---------------addOrUpdate -- user.getName(): "+user.getLogin());
        log.debug("---------------addOrUpdate -- user.getRoles().size(): "+user.getRoles().size());
        try{
            getHibernateTemplate().saveOrUpdate(user);
        } catch (Exception ex){
            log.debug("--------Cause:"+ex.getCause().getMessage()+"-------- ex: "+ex.getMessage());
        }
        
    }

    public List<User> getAll() {
        return (List<User>) getHibernateTemplate().find("from User");
    }

    @Transactional(readOnly = false)
    public void delete(long userId) {
        User user = getHibernateTemplate().load(User.class, userId);
        getHibernateTemplate().delete(user);
    }

    public User findByLogin(String login) {
        List<User> users = getHibernateTemplate().findByNamedParam("from User where login like :login", "login", login);
        return !users.isEmpty() ? users.get(0) : new User();
    }

    public User getById(long id) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}